package com.hyy.libray.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hyy.libray.contract.BaseContract;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.view.LottieEmpyCallback;
import com.hyy.libray.ui.view.LottieLoadingCallback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @ClassName: com.mala.app.live_teacher.ui.fragment
 * @Description:
 * @Author: hyy
 * @Date: 2019/6/26
 * @Time: 3:12 PM
 */
public abstract class BaseFragment<T extends IBasePresenter> extends Fragment implements BaseContract.IView {


    public T mPresenter;


    public View mRootView;


    Unbinder unbinder;

    private LoadService loadService;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mRootView = inflater.inflate(getLayoutResId(), container, false);
        unbinder = ButterKnife.bind(this, mRootView);
        mPresenter = onBasePresenter();
        loadService = LoadSir.getDefault().register(getLoadSirTarget());
        attachView();
        initView(mRootView);
        initData();


        return loadService.getLoadLayout();
    }


    public Object getLoadSirTarget() {
        return mRootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        dettachView();
    }

    public void attachView() {
        if (mPresenter != null) {
            mPresenter.onttach(this);
        }
    }


    public void dettachView() {
        if (mPresenter != null) {
            mPresenter.dettach();
        }
    }

    /**
     * 获取布局文件地址
     */
    public abstract int getLayoutResId();

    /**
     * 初始化布局
     */
    public abstract void initView(View view);

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    protected abstract T onBasePresenter();


    @Override
    public void showLoading() {
        loadService.showCallback(LottieLoadingCallback.class);
    }

    @Override
    public void disLoading() {
        loadService.showCallback(SuccessCallback.class);
    }

    @Override
    public void showErrorView(int errorResult) {
        loadService.showCallback(LottieEmpyCallback.class);
    }
}
